#!/usr/bin/perl

use DBI;

# Connect to the database
$dbh = DBI->connect("DBI:mysql:mman:",'USERHERE!','PASSWORDHERE!') or die "No database\n";

open (FILE, "virtusertable");
while (<FILE>) {
chomp;
@mapping = split(/\t+/, $_);
@fullrecipient = split(/\@/, $mapping[0]);
$domain = $fullrecipient[1];
$query1 = "INSERT IGNORE INTO domain values ('','$domain')";
$sth1 = $dbh->prepare($query1);
$sth1->execute;
}
close (FILE);


open (FILE, "virtusertable");
while (<FILE>) {
chomp;
@mapping = split(/\t+/, $_);
@fullrecipient = split(/\@/, $mapping[0]);
$username = $fullrecipient[0];
$domain = $fullrecipient[1];
$target = $mapping[1];
if ($username eq "") {
  $username = "CATCHALL";
}
$query1 = "SELECT id FROM domain WHERE name = '$domain'";
print "$query1\n";
$sth1 = $dbh->prepare($query1);
$sth1->execute or die "Can't run $query1";
$domainid = $sth1->fetchrow_array();

$insmap = "insert into mapping values ('','$domainid','$username','$target')";
$sth = $dbh->prepare($insmap);
$sth->execute or die "Can't insert\n";

print "Inserted $username to $target for domain $domainid\n";
}
close(FILE);
